#!/bin/sh
#create by liangcha<ckmx945@gmail.com>

BASE_URL='https://gitee.com/lyy888119/ipshare/tree/master/ipshare-for-k2_padavan'
WORK_PATH='/tmp/ipshare'
CONF_PATH='/etc/config'
CONF_FILE="$CONF_PATH/ipshare"
SUCC_FLAG="$WORK_PATH"/success
EXEC_BIN="$WORK_PATH"/ipshare

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$WORK_PATH

logging()
{
    logger -t "[ipshare_padavan]" "$1"
}


wget_download()
{
    [ -f $1 ] && return 0
    wget -q -T 10 -O $1  $2
    return $?
}


create_config()
{
    [ -f $CONF_FILE ] && return 0
    mkdir -p $CONF_PATH
    echo -e "config base 'server'\n\toption enable '1'\n\toption redial '1'\n\toption nolog '0'\n\toption username '$1'" > $CONF_FILE
    return $?
}


create_files()
{
    [ ! -d $WORK_PATH ] && mkdir $WORK_PATH
    cd $WORK_PATH
    wget_download libuci.so     $BASE_URL/lib/libuci.so
    [ $? -ne 0 ] && return
    logging "download libuci.so success"
    wget_download libgcc_s.so.1 $BASE_URL/lib/libgcc_s.so.1
    [ $? -ne 0 ] && return
    logging "download libgcc_s.so.1 success"
    wget_download ipshare       $BASE_URL/bin/ipshare
    [ $? -ne 0 ] && return
    chmod +x ipshare
    [ $? -ne 0 ] && return
    logging "download ipshare success"
    ln -sf /lib/libmbedtls.so libmbedtls.so.9
    [ $? -ne 0 ] && return
    logging "link libmbedtls.so.9 success"
    create_config $1
    [ $? -ne 0 ] && return
    logging "create config_file success"
    touch $SUCC_FLAG
}


do_start()
{
    while [ ! -f $SUCC_FLAG ]; do
        sleep 5
        logging "need to create all the files"
        create_files $1
    done
    logging "all file is created, start $EXEC_BIN"
    $EXEC_BIN start
    return $?
}


do_stop()
{
    logging "ipshare will be stoped"
    $EXEC_BIN stop
    return $?
}


do_restart()
{
    logging "ipshare will restart"
    $EXEC_BIN restart
    return $?
}

do_config()
{
    logging "create configure file"
    create_config $1
}


RET=0
case "$1" in
    stop|restart )
        do_$1
        RET=$?
        ;;
    start|config)
        if [ $# -ne 2 ]; then
            echo "Usage: $0 <$1> <user>"
            RET=1
        else
            do_$1 $2
            RET=$?
        fi
        ;;
    *)
        echo "Usage: $0 <start|stop|restart|config>"
        RET=1
        ;;
esac

exit $RET
